package com.alibaba.otter.manager.web.service;

import com.alibaba.otter.manager.biz.config.datamedia.DataMediaService;
import com.alibaba.otter.manager.biz.config.datamediapair.DataMediaPairService;
import com.alibaba.otter.manager.biz.dto.CommonSearchDTO;
import com.alibaba.otter.manager.web.common.model.SeniorDataMedia;
import com.alibaba.otter.shared.common.model.config.data.DataMedia;
import com.alibaba.otter.shared.common.model.config.data.DataMediaPair;
import com.mybatisflex.core.paginate.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DataMediaAggService {


    private final DataMediaService dataMediaService;


    private final DataMediaPairService dataMediaPairService;

    public DataMediaAggService(DataMediaService dataMediaService, DataMediaPairService dataMediaPairService) {
        this.dataMediaService = dataMediaService;
        this.dataMediaPairService = dataMediaPairService;
    }


    public  Page<SeniorDataMedia> page(CommonSearchDTO searchVo, Pageable pageable) {

        Page<DataMedia> page = dataMediaService.dataMediaPage(searchVo,pageable);
        List<DataMedia> dataMedias = page.getRecords();
        List<SeniorDataMedia> seniorDataMedias = new ArrayList<>();
        for (DataMedia dataMedia : dataMedias) {
            SeniorDataMedia seniorDataMedia = new SeniorDataMedia();
            seniorDataMedia.setId(dataMedia.getId());
            seniorDataMedia.setEncode(dataMedia.getEncode());
            seniorDataMedia.setGmtCreate(dataMedia.getGmtCreate());
            seniorDataMedia.setGmtModified(dataMedia.getGmtModified());
            seniorDataMedia.setName(dataMedia.getName());
            seniorDataMedia.setNamespace(dataMedia.getNamespace());
            seniorDataMedia.setSource(dataMedia.getSource());
            List<DataMediaPair> pairs = dataMediaPairService.listByDataMediaId(dataMedia.getId());
            seniorDataMedia.setPairs(pairs);
            seniorDataMedia.setUsed(!pairs.isEmpty());
            seniorDataMedias.add(seniorDataMedia);

        }
        Page<SeniorDataMedia> p = Page.of(page.getPageNumber(), page.getPageSize(), page.getTotalRow());
        p.setRecords(seniorDataMedias);
        return p;

    }
}
